package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 *
 * @author alexis
 * @date 2025-02-25
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    /**
     * 申请入住
     *
     * @param checkInApplyDto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        // 判断老人是否已经入住
        String idCardNo = checkInApplyDto.getCheckInElderDto().getIdCardNo();
        Elder elder = checkElderIsEnable(idCardNo);

        // 更新床位状态
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        Long bedId = checkInConfigDto.getBedId();
        Bed bed = updateBedStatus(bedId, 1);

        // 保存或更新老人数据
        elder = insertOrUpdate(elder, bed, checkInApplyDto.getCheckInElderDto());

        // 新增签约办理
        insertContract(checkInApplyDto, elder);

        // 新增入住信息
        CheckIn checkIn = insertCheckIn(checkInApplyDto, elder);

        // 新增入住配置信息
        insertCheckInConfig(checkInConfigDto, checkIn);
    }

    /**
     * 查询入住详情
     *
     * @param id
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckIn checkIn = checkInMapper.selectById(id);
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectById(elderId);
        if (ObjectUtil.isEmpty(elder)){
            throw new RuntimeException("老人信息查询失败");
        }
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId,id));
        if (ObjectUtil.isEmpty(checkInConfig)){
            throw new RuntimeException("入住配置信息查询失败");
        }
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig,CheckInConfigVo.class);
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        String elderFamily = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(elderFamily,ElderFamilyVo.class);
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId,elder.getId()));
        if (ObjectUtil.isEmpty(contract)){
            throw new RuntimeException("合同信息查询失败");
        }
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }

    /**
     * 新增入住配置
     *
     * @param checkInConfigDto
     */
    private void insertCheckInConfig(CheckInConfigDto checkInConfigDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     *
     * @param elder
     * @param checkInApplyDto
     * @return
     */
    private CheckIn insertCheckIn(CheckInApplyDto checkInApplyDto, Elder elder) {
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        //储存老人家属信息
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增合同
     *
     * @param elder
     * @param checkInApplyDto
     */
    private void insertContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        Contract contract = BeanUtil.toBean(checkInContractDto, Contract.class);
        contract.setElderId(elder.getId());
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(checkInConfigDto.getStartDate().isBefore(LocalDateTime.now()) ? 1 : 0);
        contractMapper.insert(contract);
    }

    /**
     * 更新或插入老人表
     *
     * @param dbElder         数据库的老人数据
     * @param bed             床位数据
     * @param checkInElderDto 入住传入的老人对象Dto
     * @return 更新或插入后的老人数据
     */
    private Elder insertOrUpdate(Elder dbElder, Bed bed, CheckInElderDto checkInElderDto) {
        Elder elder = BeanUtil.toBean(checkInElderDto, Elder.class);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        if (ObjectUtil.isNotEmpty(dbElder)) {
            elderMapper.updateById(elder);
        } else {
            elderMapper.insert(elder);
        }
        return elder;
    }

    /**
     * 更新床位状态
     *
     * @param status
     * @return
     */
    private Bed updateBedStatus(Long bedId, int status) {
        Bed bed = bedMapper.selectBedById(bedId);
        bed.setBedStatus(status);
        bedMapper.updateById(bed);
        return bed;
    }

    /**
     * 校验老人是否已入住
     *
     * @param idCardNo 老人身份证号
     * @return
     */
    private Elder checkElderIsEnable(String idCardNo) {
        Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, idCardNo));
        if (ObjectUtil.isNotEmpty(elder) && elder.getStatus() == 1) {
            throw new BaseException("老人已入住");
        }
        return elder;
    }
}
